package com.chcit.mobile.mvp.inventory.model;

import android.app.Application;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chcit.mobile.app.exception.BaseException;
import com.chcit.mobile.mvp.common.api.service.CommonService;
import com.chcit.mobile.mvp.common.api.service.UserService;
import com.chcit.mobile.mvp.entity.PackageBean;
import com.chcit.mobile.mvp.entity.ResultBean;
import com.chcit.mobile.mvp.inventory.api.InventoryApi;
import com.google.gson.Gson;
import com.jess.arms.integration.IRepositoryManager;
import com.jess.arms.mvp.BaseModel;

import com.jess.arms.di.scope.FragmentScope;

import javax.inject.Inject;

import com.chcit.mobile.mvp.inventory.contract.MovementPlanScanPackageContract;
import com.jess.arms.utils.ArmsUtils;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;

@FragmentScope
public class MovementPlanScanPackageModel extends BaseModel implements MovementPlanScanPackageContract.Model {
    @Inject
    Gson mGson;
    @Inject
    Application mApplication;

    @Inject
    public MovementPlanScanPackageModel(IRepositoryManager repositoryManager) {
        super(repositoryManager);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mGson = null;
        this.mApplication = null;
    }

    @Override
    public Observable<JSONArray> queryPackageInfo(JSONObject json) {
        return mRepositoryManager.obtainRetrofitService(CommonService.class)
                .queryPackageInfo(json)
                .map(result -> {
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    if (jsonObject.getBoolean("success")) {
                        if (jsonObject.getInteger("total") > 0) {
                            return jsonObject.getJSONArray("rows");
                        } else {
                            throw new Exception("包装不存在或已出库！");
                        }

                    } else {
                        String msg = jsonObject.getString("msg");
                        if (msg != null && !msg.isEmpty()) {
                            throw new Exception(msg);
                        } else {
                            throw new Exception("未知错误！");
                        }
                    }
                }).subscribeOn(Schedulers.io());
    }

    @Override
    public Observable<ResultBean> movementPackageSubmit(JSONObject json) {
        return mRepositoryManager.obtainRetrofitService(InventoryApi.class)
                .movementPackageConfirm(json).subscribeOn(Schedulers.io());
    }
}